﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ImdbRipperBrowser
{
  public partial class FrmMain : Form
  {
    private string currPath;
    private IEnumerable<Movie> movies;
    private Movie selectedMovie;
    private Config cfg;

    public FrmMain()
    {
      InitializeComponent();

      IESoundDisabler.DisableSounds();

      var aux = Application.ExecutablePath;
      System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(aux);
      cfg = new Config(config);

      currPath = Path.GetDirectoryName(aux);

      loadSizeConfiguration();

      loadBrowserPanelConfiguration();

      loadSplitterConfiguration();

      if (!imdbRipperFilesPathIsValid())
        setImdbRipperFilesPath();
      else
        loadMovies();
    }

    private string getImdbRipperFilesPath()
    {
      if (Path.IsPathRooted(cfg.ImdbRipperFilesPath))
        return cfg.ImdbRipperFilesPath;
      else
        return Path.GetFullPath(Path.Combine(currPath, cfg.ImdbRipperFilesPath));
    }

    private bool imdbRipperFilesPathIsValid()
    {
      if (string.IsNullOrEmpty(cfg.ImdbRipperFilesPath))
        return false;

      return Directory.Exists(getImdbRipperFilesPath());
    }

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
      switch (keyData) 
      { 
        case (Keys.Control | Keys.P): 
          { 
            toolStripButtonSelectPath.PerformClick(); 
            break; 
          }
        case (Keys.Control | Keys.T):
          {
            toolStripButtonToggleBrowser.PerformClick();
            break;
          }
        case (Keys.Control | Keys.O):
          {
            toolStripButtonChangeOrientation.PerformClick();
            break;
          }
      } 
      
      return base.ProcessCmdKey(ref msg, keyData); 
    }

    private void loadSizeConfiguration()
    {
      if (cfg.Height > 0)
        this.Height = cfg.Height;

      if (cfg.Width > 0)
        this.Width = cfg.Width;

      if (cfg.StartMaximized)
        this.WindowState = FormWindowState.Maximized;
    }

    private void loadSplitterConfiguration()
    {
      splitContainer1.SplitterDistance = cfg.SplitterPosition;
      splitContainer1.Orientation = cfg.SplitterOrientation;

      toolStripButtonChangeOrientation.Checked = (splitContainer1.Orientation == Orientation.Vertical);
    }

    private void loadBrowserPanelConfiguration()
    {
      toolStripButtonToggleBrowser.Checked = cfg.ShowBrowser;
      setBrowserPanelCollapsed();
    }

    private void saveSizeConfiguration()
    {
      if (this.WindowState != FormWindowState.Maximized)
      {
        cfg.Height = this.Height;
        cfg.Width = this.Width;
      }

      cfg.StartMaximized = this.WindowState == FormWindowState.Maximized;

      cfg.Save();
    }

    private void saveSplitterConfiguration()
    {
      cfg.SplitterPosition = splitContainer1.SplitterDistance;
      cfg.SplitterOrientation = splitContainer1.Orientation;
      cfg.Save();
    }

    private void saveBrowserPanelConfiguration()
    {
      cfg.ShowBrowser = toolStripButtonToggleBrowser.Checked;
      cfg.Save();
    }

    private void loadMovies()
    {
      dataGridView1.DataSource = null;
      webBrowser1.Navigate(string.Empty);

      string path = getImdbRipperFilesPath();
      labelImdbRipperPath.Text = path;

      if (imdbRipperFilesPathIsValid())
      {
        var repo = new MovieRepository(path);
        movies = repo.FindAll();

        dataGridView1.DataSource = movies;
      }
    }

    private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex >= 0)
      {
        selectedMovie = (dataGridView1.Rows[e.RowIndex].DataBoundItem as Movie);
        if (cfg.ShowBrowser)
          webBrowser1.Navigate(selectedMovie.ImdbUrl);
      }
      else
        selectedMovie = null;
    }

    private void dataGridView1_RowHeightInfoNeeded(object sender, DataGridViewRowHeightInfoNeededEventArgs e)
    {
      if (movies.ElementAt(e.RowIndex).Thumbnail != null)
        e.Height = movies.ElementAt(e.RowIndex).Thumbnail.Height;
    }

    private void setBrowserPanelCollapsed()
    {
      splitContainer1.Panel2Collapsed = !toolStripButtonToggleBrowser.Checked;
      if (!splitContainer1.Panel2Collapsed && (selectedMovie != null))
      {
        if (movies.Contains(selectedMovie))
          webBrowser1.Navigate(selectedMovie.ImdbUrl);
      }
    }

    private void setImdbRipperFilesPath()
    {
      using (FolderBrowserDialog dialog = new FolderBrowserDialog())
      {
        dialog.Description = "Select the path where the ImdbRipper xml files are located";
        dialog.ShowNewFolderButton = false;

        if (imdbRipperFilesPathIsValid())
        {
          dialog.SelectedPath = getImdbRipperFilesPath();
        }

        if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
          var uri1 = new Uri(dialog.SelectedPath + Path.DirectorySeparatorChar);
          var uri2 = new Uri(currPath + Path.DirectorySeparatorChar);
          var path = uri2.MakeRelativeUri(uri1).ToString();
          path = path.Replace('/', '\\');

          cfg.ImdbRipperFilesPath = path;
          cfg.Save();

          loadMovies();
        }
      }
    }

    private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
    {
      saveSplitterConfiguration();

      saveSizeConfiguration();
    }

    private void toolStripButton1_Click(object sender, EventArgs e)
    {
      setImdbRipperFilesPath();
    }

    private void toolStripButton2_Click(object sender, EventArgs e)
    {
      setBrowserPanelCollapsed();

      saveBrowserPanelConfiguration();
    }

    private void toolStripButton1_Click_1(object sender, EventArgs e)
    {
      if (toolStripButtonChangeOrientation.Checked)
        splitContainer1.Orientation = Orientation.Vertical;
      else
        splitContainer1.Orientation = Orientation.Horizontal;
    }
  }
}
